# coding: utf-8
# Author: Legend奇
# Time： 2020/7/17 下午1:33
import os
import sys
from dataclasses import dataclass

from ngs.tools import config

__all__ = [
    'CONFIG',
    'OplatformConfig',
]
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'configs/system.yaml')
if not os.path.exists(CONFIG_PATH):
    raise Exception(f'未找到配置文件: {CONFIG_PATH}')

_CONFIG_DICT = config.load_config(CONFIG_PATH)


@dataclass()
class AsgiConfig(config.BasicConfig):
    max_threads: int


@dataclass()
class WebServerConfig(config.IpAddressConfig):
    port: int


@dataclass()
class LogConfig(config.LogConfig):
    running_log_name: str = 'running.log'
    error_log_name: str = 'error.log'
    query_log_name: str = 'query.log'

    def get_config(self):
        log_config = {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'verbose': {
                    'format': '[{asctime}][{levelname}][{pathname}:{lineno:d}]: {message}',
                    'datefmt': '%Y-%m-%d %H:%M:%S',
                    'style': '{'
                },
                'exception': {
                    'format': '[{asctime}]: {message}',
                    'datefmt': '%Y-%m-%d %H:%M:%S',
                    'style': '{'
                }
            },
            'handlers': {
                'file': {
                    'level': self.level,
                    'class': 'logging.handlers.TimedRotatingFileHandler',
                    'filename': os.path.join(self.dir, self.running_log_name),
                    'formatter': 'verbose',
                    'encoding': 'utf-8',
                    'when': 'D',
                    'interval': 1,
                    'backupCount': 30
                },
                'error': {
                    'level': self.level,
                    'class': 'logging.handlers.TimedRotatingFileHandler',
                    'filename': os.path.join(self.dir, self.error_log_name),
                    'formatter': 'exception',
                    'encoding': 'utf-8',
                    'when': 'D',
                    'interval': 1,
                    'backupCount': 30
                },
                'query': {
                    'level': 'DEBUG',
                    'class': 'logging.handlers.TimedRotatingFileHandler',
                    'filename': os.path.join(self.dir, self.query_log_name),
                    'formatter': 'verbose',
                    'encoding': 'utf-8',
                    'when': 'D',
                    'interval': 1,
                    'backupCount': 30
                },
                'console': {
                    'level': 'DEBUG',
                    'class': 'logging.StreamHandler',
                    'stream': sys.stdout,
                    'formatter': 'verbose',
                }
            },
            'loggers': {
                self.running_log_name: {
                    'handlers': ['file'],
                    'level': self.level,
                    'propagate': True,
                },
                self.query_log_name: {
                    'handlers': ['error'],
                    'level': 'ERROR',
                    'propagate': True
                },
                # 'django.db.backends': {
                #     'handlers': ['query'],
                #     'level': 'DEBUG',
                #     'propagate': True
                # }
            },
        }

        for key, value in log_config['loggers'].items():
            if key in CONFIG.log.console:
                if 'console' not in value['handlers']:
                    value['handlers'].append('console')

        return log_config


@dataclass()
class DpiConfig(config.BasicConfig):
    pcap_query: str
    pcap_query_callback: str
    ftp_type: str


@dataclass()
class SftpConfig(config.IpAddressConfig):
    username: str
    password: str
    port: int
    dir: str


@dataclass()
class OplatformConfig(config.BasicConfig):
    priority_ip_type: int
    influx_query_type: int
    log: LogConfig
    asgi: AsgiConfig
    webserver: WebServerConfig
    mysql: config.MysqlConfig
    influxdb: config.InfluxdbConfig
    redis: config.RedisConfig
    grpc_server: config.GrpcServerConfig
    app_dpi: DpiConfig
    sftp: SftpConfig
    base_dir = None

    def init(self):
        for name, attrs in self.__dict__.items():
            if isinstance(attrs, config.BasicConfig):
                attrs.init()
        self.base_dir = os.path.dirname(os.path.abspath(__file__))


_log = LogConfig(**_CONFIG_DICT['log'])

_asgi = AsgiConfig(
    **_CONFIG_DICT['asgi']
)

_grpc_server = config.GrpcServerConfig(
    **_CONFIG_DICT['grpc_server']
)

_web_server_config = WebServerConfig(
    **_CONFIG_DICT['webserver']
)

_mysql = config.MysqlConfig(
    **_CONFIG_DICT['mysql']
)

_redis = config.RedisConfig(
    **_CONFIG_DICT['redis']
)

_influxdb = config.InfluxdbConfig(
    **_CONFIG_DICT['influxdb']
)

_app_dpi = DpiConfig(**_CONFIG_DICT['app_dpi'])

_sftp = SftpConfig(**_CONFIG_DICT['sftp'])

CONFIG = OplatformConfig(
    log=_log,
    asgi=_asgi,
    priority_ip_type=_CONFIG_DICT['priority_ip_type'],
    influx_query_type=_CONFIG_DICT['influx_query_type'],
    webserver=_web_server_config,
    mysql=_mysql,
    influxdb=_influxdb,
    redis=_redis,
    grpc_server=_grpc_server,
    app_dpi=_app_dpi,
    sftp=_sftp
)

CONFIG.init()

